home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Source Code / C / Applications / SML⁄NJ 93+ / Documentation / examples / awk / awk.sml next >
Encoding:
Text File  |  1995-12-30  |  1023 b   |  46 lines  |  [TEXT/R*ch]

  1. (* awk.sml *)
  2.  
  3. signature AWK =
  4. sig
  5.   val makeInt : string -> int  (* translates a digit string into an int *)
  6.   val awk : instream * (string list  -> unit) * (unit -> unit) -> unit
  7. end
  8.  
  9. structure Awk : AWK =
  10. struct
  11.  
  12.   val digit0 = ord "0"
  13.   and digit9 = ord "9"
  14.   exception MakeInt
  15.   fun makeInt (s:string) : int =
  16.       (* translates string s into an integer.
  17.          Bug: doesn't deal with negative integers *)
  18.       let val len = size s
  19.       fun translate(i,n) =
  20.           if i<len
  21.           then let val c = ordof(s,i)
  22.             in if digit0 <= c andalso c <= digit9
  23.                then translate(i+1,10*n+c-digit0)
  24.                else raise MakeInt
  25.            end
  26.           else n
  27.        in translate(0,0)
  28.       end
  29.  
  30.   exception END
  31.  
  32.   fun parseStream (instream) = 
  33.       fn () => if end_of_stream instream
  34.            then raise END
  35.            else Lex2.words(input_line(instream))
  36.  
  37.   fun awk(instream,step,final) =
  38.       let val lines = parseStream instream
  39.       fun iter () = (step(lines()); iter())
  40.        in iter() handle END => final()
  41.       end
  42.  
  43. end
  44.  
  45.  
  46.